<template>
  <div>
    <page-view>
      <template #option>
        <div class="btn-box">
          <el-button type="primary" @click="add">新增</el-button>
          <el-button type="primary" :loading="importLoading" @click="importDictTree">导入</el-button>
        </div>

      </template>

      <template #form>

        <SearchForm :data-form="formInline" @on-search="onSearch" @onReset="onSearch">
          <el-form-item prop="orgCode" label-width="73px">
            <el-cascader :options="treeDatas" :props="CONMPAYN_PROPS" placeholder="请选择组织机构" clearable style="width:100%"
              v-model="formInline.orgCode" />
          </el-form-item>
          <el-form-item prop="codeOrName" label-width="130px">
            <el-input v-model="formInline.codeOrName" placeholder="请输入名称/编码" clearable />
          </el-form-item>
        </SearchForm>
      </template>
      <template #table="tableScope">
        <PubilcTable :table-data="tableData" :isSlot="false" :tableHeight="tableScope.tableHeight"
          :list-config="SUBJECT_LIST_CONFIG" @on-action="onAction" :actionLimit="actionLimit"
          :translateTextDeal="translateTextDeal" :pageData="pageData" />
      </template>
    </page-view>
    <subjectAddOrEdit :dialogVisible="dialogVisible" :type="type" @handleClose="handleClose" :dataForm="dataForm"
      @on-update="onSearch" :treeDatas="treeDatas"></subjectAddOrEdit>
    <importForm :dialog-visible="dialogVisible2" :downLoading='downLoading' :showDown="true"
      :acceptOption='acceptOption' @on-submit="exportFiled" @downFile="downFile" @handle-close="handleClose" />
  </div>
</template>
<script  setup >

import { SUBJECT_LIST_CONFIG, STATUS_LIST, CONMPAYN_PROPS } from './Common/config'
import { ElMessage, ElMessageBox } from 'element-plus'
import { statusText, singleArr, treeData } from '@/util/index'
import api from '@/api'
import { useUserStore } from '@/store/index'
import subjectAddOrEdit from './Common/subjectAddOrEdit.vue'
import { xhrFile, downloadFile } from "@/util/downFile";

const formInline = ref({
  codeOrName: '',
  orgCode: []
})

const tableData = ref([])

const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const userStore = useUserStore()

const type = ref('add')

const dialogVisible = ref(false)

const dialogVisible2 = ref(false)

const acceptOption = ref('.xls,.xlsx')

const importLoading = ref(false)

const downLoading = ref(false)

const dataForm = ref({
  orgCode: '',
  categoryName: '',
  categoryCode: '',
  enabled: true,
})
const treeDatas = ref([])

onMounted(() => {

  getCompayTree()
})



const onSearch = () => {
  pageData.value.pageNum = 1
  getList()

}

// 获取列表数据
const getList = () => {
  const parms = {
    ...pageData.value,
    ...formInline.value
  }
  parms['orgCode'] = parms['orgCode'].length > 0 ? parms['orgCode'][parms['orgCode'].length - 1] : ''
  api.budgetConfig.budgetSubjectList(parms).then(res => {
    const { list, total } = res
    tableData.value = list
    console.log(total, 'total')
    pageData.value.total = total
    console.log(pageData.value)
  })
}


const delRow = (row) => {
  ElMessageBox.confirm(
    '您确定要进行删除操作吗?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      api.budgetConfig.budgetSubjectDelete({ id: row.id }).then(res => {
        onSearch()
        ElMessage.success('操作成功')
      })
    })

}


const handleClose = () => {
  dialogVisible.value = false
  dialogVisible2.value = false
}

const editRow = (row) => {
  type.value = 'edit'
  let obj = { ...row }
  obj['path'] = userStore.userInfo.departmentVo.path
  dataForm.value = obj
  dialogVisible.value = true
}
// 列表操作 分页
const onAction = ([item, row]) => {
  const obj = {
    'del': delRow,
    'edit': editRow,
    'pageNum': getList,
    'pageSize': onSearch
  }
  if (typeof item === 'string') {
    pageData.value[item] = row
    obj[item]()
  } else {
    obj[item.alias](row)
  }

}
// 显示新增弹框
const add = () => {
  dataForm.value = {
    orgCode: '',
    categoryName: '',
    categoryCode: '',
    enabled: true,
  }
  type.value = 'add'
  dialogVisible.value = true

}
const translateTextDeal = (item, val) => {
  return statusText(STATUS_LIST, val)

}
const actionLimit = ([item, row]) => {

  const departmentId = userStore.userInfo.departmentVo.departmentId
  let flag = false
  if (row.alias == 'del' && item.orgCode != departmentId) flag = true
  if (row.alias == 'edit' && item.orgCode != departmentId) flag = true
  return flag
}
const getCompayTree = () => {
  const path = userStore.userInfo.departmentVo.path
  const pathArr = path.split("-")
  api.user.userGetConmpanyTree().then(res => {
    // 只能显示自己和自己以上的组织
    let arr = singleArr(res)
    let result = arr.filter(item => {
      if (path == `${item.parentId}-${item.id}` || (pathArr.includes(item.id))) {
        return item
      }
    })
    result.forEach(item => {
      if (item.children) {
        delete item.children
      }
    })
    treeDatas.value = treeData(result, 'id', 'parentId', '0')
    formInline.value.orgCode = pathArr
    getList()
  })
}
// 导入提交
const exportFiled = (val) => {
  if (val && val.file) {
    let fd = new FormData()
    fd.append('file', val.file)
    api.budgetConfig.budgetSubjectExportIn(fd).then((res) => {
      ElMessage({
        type: 'success',
        message: '导入成功!'
      });
      importLoading.value = false
      getList()
    })
  }
}
// 下载导入模板
const downFile = () => {
  downLoading.value = true;
  api.publicApi.downFile("budgetSubject").then((res) => {
    xhrFile(res.url).then((rex) => {
      downloadFile(rex, "预算科目导入模板");
      downLoading.value = false;
      ElMessage({
        type: "success",
        message: "下载成功!",
      });
    });
  });
};


const importDictTree = () => {
  dialogVisible2.value = true
}
</script>
<style lang="scss" scoped>
</style>
